<template>
	<div class="login-container center-box aa">
		<div id="c1">

		</div>
		<div class="table-cell">
			<div class="center-form">
				<router-link to="/home" class="cf-logo pc-vertical"><img :src="logo" /></router-link>
				<!-- <a href="#" class="cf-logo pc-vertical"></a> -->
				<!-- <router-link to="/busLogin" v-if="$route.path != '/busLogin'"  class="change-version">商家版</router-link> -->
				<!-- <router-link to="/userLogin"   class="change-version">个人版</router-link> -->
				<!-- <a href="businesslogin.html" class="change-version">商家版</a> -->
				<p class="title">登录</p>
				<!-- 账号密码登陆 -->
				<div class="form-box" v-if="isAccount">
					<p class="desc">
						通过您的账号密码登录企业，或<a href="javascript:;" @click="changeLoginType(0)">手机验证码</a>
					</p>
					<el-form ref="form" :rules="rules" class="form-box" :model="form" label-width="80px">
						<el-form-item prop="phone">
							<el-input placeholder="请输入手机号/邮箱" v-model.trim="form.phone" class="input-with-select">
							</el-input>
						</el-form-item>
						<el-form-item prop="pass">
							<el-input placeholder="请输入密码" :type="iptType" v-model.trim="form.pass" class="input-with-select">
								<i slot="suffix" class="el-input__icon el-icon-view" @click="changeIptType"></i>
							</el-input>
						</el-form-item>
						<div class="fb-link">
							<router-link to="/forgetPassword">忘记密码</router-link>
							<!-- <a href="forgetPassword.html">忘记密码</a> -->
						</div>
						<el-form-item>
							<div class="fb-submit">
								<button class="btn-submit" type="button" @click="submitForm('form')">
									登陆
								</button>
							</div>
						</el-form-item>
					</el-form>
				</div>
				<!-- 手机验证码登陆 -->
				<div class="form-box" v-else>
					<p class="desc">
						通过您的手机号码登录企业，或<a href="javascript:;" @click="changeLoginType(1)">账号密码登陆</a>
					</p>
					<el-form ref="form1" :rules="rules" class="form-box" :model="form1" label-width="80px">
						<!-- <el-form-item prop="phone">
		                <el-input placeholder="请输入手机号" v-model.trim="form1.phone" class="input-with-select">
		                </el-input>
		            </el-form-item> -->

						<div style="position:relative">
							<div style="position:absolute;top:38%;left:3%;z-index:2">
								<img :src="phoneAreaData[0].img_url" alt="" />
							</div>
							<el-form-item prop="phone" label-width="80px">
								<el-input placeholder="请输入手机号" v-model.trim="form1.phone" class="input-with-select ">
									<!-- new select -->
									<el-select size="mini" class="text_center" slot="prepend" v-model="phoneArea" placeholder="请选择">
										<el-option v-for="item in phoneAreaData" :key="item.lower_CN_name" :label="item.area_code" :value="
                                                item.lower_CN_name +
                                                    item.area_code
                                            "
										 :disabled="
                                                item.lower_CN_name !== '中国'
                                            ">
											<img :src="item.img_url" alt="" />
											<span style="padding-left:10px;">{{ item.lower_CN_name
                                                }}{{ item.area_code }}</span>
										</el-option>
									</el-select>
								</el-input>
							</el-form-item>
						</div>

						<el-form-item class="yzm" prop="yzm">
							<el-input placeholder="请输入验证码" v-model.trim="form1.yzm" class="input-with-select"></el-input>
							<div class="box">
								<a v-if="isYZMShow" href="javascript:;" class="btn-get-code" @click="getYZM">获取短信验证码</a>
								<div v-else class="timer">{{ time }} s</div>
							</div>
						</el-form-item>
						<div class="fb-link">
							<router-link to="/forgetPassword">忘记密码</router-link>
							<!-- <a href="forgetPassword.html">忘记密码</a> -->
						</div>
						<el-form-item>
							<div class="fb-submit">
								<button class="btn-submit" type="button" @click="submitForm('form1')">
									登陆
								</button>
							</div>
						</el-form-item>
					</el-form>
				</div>
				<div class="other-choice">
					或
					<router-link to="/userregister" v-if="$route.path == '/userLogin'">去注册</router-link>
					<!-- <router-link to="/busregister"  v-else>商家注册</router-link> -->
				</div>
				<div class="login-switch" :class="checked ? 'form' : 'weixin'" @click="checkCode">
					<span></span>
					<div class="icon-bg"></div>
				</div>
				<div class="ercode" v-show="ercode">
					<div id="weixin-login" class="weixin-login">
						<div class="weixin-login-code">
							<div id="qrcode"></div>
							<!-- <div @click="generateCode" v-if="weChatAuthorized">
							<div class="get-qr-code-msg">二维码已失效，点击重新加载二维码</div>
						</div> -->
						</div>
					</div>
				</div>
				<div class="weixin-bind-account" v-if="bindaccount">
					<h1 data-title="LOGIN" class="form-title l" data-lang="login">
						微信扫码登录
					</h1>
					<p>
						该微信账号没有绑定<span id="app_name">猪爸爸平台</span>，您可以选择绑定一个已有的账号或者创建一个新账号。
					</p>
					<div>
						<button class="btn-form l" @click="bindExistingAccountFrom">
							绑定已有账号
						</button>
					</div>
					<div>
						<router-link class="btn-form l" id="bind-new-account" to="/weixinregister">创建新账号</router-link>
					</div>
				</div>
				<div class="bind_account" v-if="bindaccountFrom">
					<!-- <div class="bind_account"> -->
					<h1 data-title="BINDING" class="form-title">绑定旧账号</h1>
					<p class="desc" v-if="accountLogin">
						通过您的账号密码绑定，或<a href="javascript:;" @click="bindaccountType(0)">手机验证码</a>
					</p>
					<p class="desc" v-if="accountLogin2">
						通过您的账号密码绑定，或<a href="javascript:;" @click="bindaccountType(1)">账号密码登陆</a>
					</p>
					<el-form ref="form2" :rules="rules2" class="form-box" :model="form2" label-width="80px">
						<el-form-item prop="phone">
							<el-input placeholder="请输入手机号" v-model.trim="form2.phone" class="input-with-select">
							</el-input>
						</el-form-item>
						<el-form-item prop="password" v-if="phoneCode">
							<el-input placeholder="请输入密码" type="password" v-model.trim="form2.password" class="input-with-select">
							</el-input>
						</el-form-item>
						<el-form-item class="yzm" prop="yzm" v-if="!phoneCode">
							<el-input placeholder="请输入验证码" v-model.trim="form2.yzm" class="input-with-select"></el-input>
							<div class="box">
								<a v-if="isYZMShow2" href="javascript:;" class="btn-get-code" @click="getYZM2">获取短信验证码</a>
								<div v-else class="timer">{{ time }} s</div>
							</div>
						</el-form-item>
						<el-form-item>
							<div class="fb-submit">
								<button class="btn-submit" type="button" @click="bingSubmitForm('form2')">
									立即绑定
								</button>
							</div>
						</el-form-item>
					</el-form>
					<div class="other-choice">
						或
						<router-link to="/weixinregister">去注册</router-link>
					</div>
				</div>
			</div>
		</div>
		<copy></copy>
	</div>
</template>

<script>
	import copy from "@/components/copyRight.vue";
	import logo from "@/assets/images/logo.png";
	const uuidv4 = require('uuid/v1');
	export default {
		components: {
			copy
		},
		data() {
			var validatephone = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('手机号不能为空'));
				}
				if (!(/^1[3456789]\d{9}$/.test(value))) {
					return callback(new Error('手机号格式不正确!'));
				}
				callback();
			};
			var validateyzm = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('验证码不能为空'));
				}

				callback();
			};
			var validateemail = (rule, value, callback) => {

				if (!value) {
					return callback(new Error('邮箱不能为空！'));
				}
				if (!(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))) {
					return callback(new Error('邮箱格式不正确!'));
				}
				callback();
			};
			var validatepass = (rule, value, callback) => {

				if (!value) {
					return callback(new Error('密码不能为空'));
				}

				callback();
			};
			return {
				jump_page: '', // 登录成功后跳转的页面
				phoneAreaData: [],
				phoneArea: "中国+86",
				isYZMShow: true,
				isYZMShow2: true,
				isAccount: true,
				iptType: "password",
				logo,
				time: 60,
				form: {
					phone: "",
					yzm: "",
					email: "",
					pass: ""
				},
				form1: {
					phone: "",
					yzm: "",
				},
				rules: {
					phone: [{
						validator: validatephone,
						trigger: 'blur'
					}],
					yzm: [{
						validator: validateyzm,
						trigger: 'blur'
					}],
					email: [{
						validator: validateemail,
						trigger: 'blur'
					}],
					pass: [{
						validator: validatepass,
						trigger: 'blur'
					}],
				},
				checked: true,
				ercode: false,
				bindaccount: false,
				bindaccountFrom: false,
				weChatAuthorized: true,
				uuid: '',
				form2: {
					phone: '',
					password: '',
					yzm: ''
				},
				rules2: {
					phone: [{
						validator: validatephone,
						trigger: 'blur'
					}],
					password: [{
						validator: validatepass,
						trigger: 'blur'
					}],
					yzm: [{
						validator: validateyzm,
						trigger: 'blur'
					}],
				},
				phoneCode: true,
				accountLogin: true,
				accountLogin2: false,
				wechat: false,
				myCaptcha:'',
                ifPs:true,
			}
		},
		mounted() {
			// this.generateCode();
			this.getAreaCode();
			this.myCaptcha = _dx.Captcha(document.getElementById('c1'), {
				appId: '064c0824fa2e57bd1251f527ea54523f', //appId，在控制台中“应用管理”或“应用配置”模块获取
				style:'popup',
                _noLogo: true,
				success:  (token)=> {
					this.myCaptcha.hide();
					if(this.ifPs){
                        this.login();
                    }else {
                        this.postYZM(); // 向后台请求数据
                        this.isYZMShow = !this.isYZMShow;
                        let i = 60;
                        var timer = setInterval(() => {
                            i--;
                            if (i == 0) {
                                this.isYZMShow = !this.isYZMShow;
                                clearInterval(timer);
                                i = 60;
                            } else {
                                this.time = i;
                            }
                        }, 1000)
                    }
				}
			});
		},
		created() {
			if (this.jump_page) this.jump_page = this.$route.query.jump_page;
		},
		methods: {
			onSuccess(){
						this.$refs.form.validate((valid) => {
							if (valid) {
								this.login();
							} else {
								return false;
							}
						});
			},
			onFail(){

			},
			onRefresh(){

			},
			getAreaCode() {
				let self = this;
				let url = '/area/getAreaCode';
				this.$ajax.get(url)
					.then((res) => {
						if (res.data.code == 0) {
							self.phoneAreaData = res.data.data
						}
					})
			},
			bindaccountType(val) {
				if (val == 0) {
					this.accountLogin = false;
					this.accountLogin2 = true;
					this.phoneCode = !this.phoneCode;
				} else {
					// this.phoneCode = true;
					this.phoneCode = !this.phoneCode;
					this.accountLogin2 = false;
					this.accountLogin = true;
				}
			},
			//微信绑定
			bingSubmitForm(formName) {
				// let params = {

				// }
				let uuid = sessionStorage.getItem('uuid')
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$ajax.post("/weiChat/bandUser", {
							state: uuid,
							mobile: this.form2.phone,
							pwd: this.accountLogin ? this.form2.password : null,
							verifyCodeL: !this.accountLogin ? this.form2.yzm : null
						}).then(res => {
							if (res.data.code == 0) {
								localStorage.setItem("key", JSON.stringify(res.data.data.sessionKey));
								this.$ajax.defaults.headers.common['user-session'] = res.data.data.sessionKey;
								this.$message({
									message: '绑定成功!',
									type: 'success'
								})
								this.$router.push('/info')
							} else if (res.data.code == 207) {
								this.$message({
									message: res.data.msg + ',请更换账号！',
									type: 'error'
								});
								this.form2 = {
									phone: '',
									password: '',
									yzm: ''
								}
							} else {
								this.$message({
									message: '账号不存在,请选择注册新用户!',
									type: 'error'
								});
								this.form2 = {
									phone: '',
									password: '',
									yzm: ''
								}
							}
						}).catch(err => {
							console.log(err, '绑定账号异常！')
						})
					} else {
						return false;
					}
				});
			},
			bindExistingAccountFrom() {
				this.bindaccountFrom = true;
			},
			generateCode() {
				let uuid = uuidv4().replace(/-/g, "");
				this.$set(this, 'uuid', uuid);
				sessionStorage.setItem('uuid', uuid);
				let obj = new WxLogin({
					self_redirect: true,
					id: "qrcode",
					appid: "wxf46ce9d30982c5c2",
					scope: "snsapi_login",
					redirect_uri: "https%3A%2F%2Fapi.zhubaba.cn%2FweiChat%2FcallBack",
					state: uuid,
					style: "black",
					href: `data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZXsNCiAgd2lkdGg6IDIwMHB4ICFpbXBvcnRhbnQ7DQp9DQouaW1wb3dlckJveHsNCiAgbWFyZ2luLXRvcDogNTVweCAhaW1wb3J0YW50Ow0KfQ==`
				});
				// this.weChatAuthorized = !this.weChatAuthorized

				let timer = setInterval((uuid) => {
					this.wxLoginStatus(uuid, timer)
				}, 2000, uuid);

			},
			wxLoginStatus(uuid, timer) {
				this.$ajax.post("/weiChat/wxLoginStatus", {
					state: uuid
				}).then(res => {
					if (res.data.data == '02') {
						clearInterval(timer);
						this.$message({
							message: '扫码登录成功,但是系统无此用户,请绑定注册',
							type: 'success'
						})
						this.bindaccount = true;
						this.ercode = false;
					} else if (res.data.data == '00') {

					} else {
						this.ercode = false;
						clearInterval(timer);
						localStorage.setItem("key", JSON.stringify(res.data.data));
						this.$ajax.defaults.headers.common['user-session'] = res.data.data;
						this.$message({
							message: '微信登录成功',
							type: 'success'
						})
						this.$router.push('/info')
						//第三方登录状态
						this.wechat = true;
						this.$store.commit('wechat', this.wechat)
					}
				}).catch(err => {})
			},
			checkCode() {
				this.generateCode();
				this.checked = !this.checked;
				this.ercode = !this.ercode;
			},
			postYZM() {
				this.$ajax.post("/user/sendMobileCode", {
						type: 1,
						mobile: this.form1.phone
					})
					.then((res) => {

						if (res.data.code == 0) {
							this.$message({
								message: '验证码发送成功!',
								type: 'success'
							});
							// window.location.href = "register-bus-step02.html";
						} else [
							this.$message.error(res.data.msg)
						]
					})
			},
			login() {
				this.$ajax.post("/user/login", {
						loginType: this.isAccount == true ? 0 : 1,
						mobile: this.isAccount == true ? this.form.phone : this.form1.phone,
						pwd: this.form.pass,
						verifyCode: this.form1.yzm,
					})
					.then((res) => {
						if (res.data.code == 0) {
							localStorage.setItem("key", JSON.stringify(res.data.data.sessionKey));
							
							// 增加COOKIES
							var c_name="usid";
							var expiredays = 365*10;
							var exdate=new Date();  
							exdate.setDate(exdate.getDate()+expiredays);  
							document.cookie=c_name+"="+escape(res.data.data.sessionKey)+((expiredays==null)?"":";expires="+exdate.toGMTString()+";path=/;domain=.zhubaba.cn");
							//end 
							// 增加COOKIES
							
							
							this.$ajax.defaults.headers.common['user-session'] = res.data.data.sessionKey;
							if (this.$route.query.back) {
								this.$message({
									message: '登陆成功，1秒后跳转到起名页!',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.push(this.$route.query.back);
								}, 1000)
							} else if (this.$route.query.jump_path) {
								this.$message({
									message: '登陆成功，1秒后跳转到经典起名页!',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.push(this.$route.query.jump_path);
								}, 1000)
							} else if(this.$route.query.vip_path){
								this.$message({
									message: '登陆成功，1秒后跳转到VIP界面!',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.push(this.$route.query.vip_path);
								}, 1000)
							} else if(this.$route.query.poetry_path){
								this.$message({
									message: '登陆成功，1秒后跳转到诗词起名界面!',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.push(this.$route.query.poetry_path);
								}, 1000)
							}else {
								this.$message({
									message: '登陆成功，1秒后跳转到首页!',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.push("/info");
								}, 1000)
							}



						} else {
							this.$message.error(res.data.msg);
						}
					})
			},
			onSubmit() {},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
					    if(this.ifPs){
                            this.myCaptcha.reload()
                            this.myCaptcha.show();
                        }else {
                            this.login();
                        }
					} else {
						return false;
					}
				});
			},
			//绑定微信账号后去验证码
			getYZM2() {
				if (this.form2.phone == "") {
					this.$message.error('手机号不能为空!');
					return;
				}
				if (!(/^1[3456789]\d{9}$/.test(this.form2.phone))) {
					this.$message.error('手机格式不正确!');
					return;
				}
				this.postYZM2(); // 向后台请求数据
				this.isYZMShow2 = !this.isYZMShow2;
				let i = 60;
				var timer = setInterval(() => {
					i--;
					if (i == 0) {
						this.isYZMShow2 = !this.isYZMShow2;
						clearInterval(timer);
						i = 60;
					} else {
						this.time = i;
					}

				}, 1000)
			},
			postYZM2() {
				this.$ajax.post("/user/sendMobileCode", {
						type: 1,
						mobile: this.form2.phone
					})
					.then((res) => {

						if (res.data.code == 0) {
							this.$message({
								message: '验证码发送成功!',
								type: 'success'
							});
							// window.location.href = "register-bus-step02.html";
						} else [
							this.$message.error(res.data.msg)
						]
					})
			},
			getYZM() {
				if (this.form1.phone == "") {
					this.$message.error('手机号不能为空!');
					return;
				};
				if (!(/^1[3456789]\d{9}$/.test(this.form1.phone))) {
					this.$message.error('手机格式不正确!');
					return;
				};
                this.myCaptcha.reload();
                this.myCaptcha.show();
			},
			changeIptType() {
				this.iptType == "password" ? this.iptType = "text" : this.iptType = "password"
			},
			changeLoginType(val) {
				if (val == 1) {
					this.$refs["form1"].resetFields();
					this.isAccount = !this.isAccount;
					this.ifPs=true;
				} else {
					this.$refs["form"].resetFields();
					this.isAccount = !this.isAccount;
                    this.ifPs=false;
				}
			}
		}
	}
</script>
<style scoped>
	#c1{
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate3d(-50%,-50%,0);
		z-index: 999999;
	}
</style>
<style>
.login-container{
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-top: 100px;
}
	.text_center input {
		text-align: center !important;
	}

	.el-input-group__prepend {
		width: 100px !important;
	}
</style>
